package com.scopionstudio.housemusic;

import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.scopionstudio.housemusic.adapter.DialogQuitApp;
import com.scopionstudio.housemusic.adapter.MusicAdapter;
import com.scopionstudio.housemusic.data.objData;
import com.scopionstudio.housemusic.parser.ParserJson;
import com.scopionstudio.housemusic.parser.ParserMusic;
import com.scopionstudio.houser.music.utils.Utils;
public class MainActivity extends Activity implements
		OnBufferingUpdateListener, OnItemClickListener {
	private String TAG = "MainActivity";
	private ParserMusic parser;
    private ImageView imgPlay;
    private TextView txtName;
    private ParserJson jsonParser;
    private ArrayList<objData> arrData;
	private MediaPlayer mPlayer;
    private String urlLoaded;
	int page = 1;
    private ListView lv;
	int countItems = 0, item = 0;
	int ID_CHECK_FIRST = -1000;
	boolean CHECK_CLICK = false;
	private Runnable notification;
	private static final String URL = "url";
	private final Handler handler = new Handler();
	private loadData mData;
	String linkCurrent = "";
	boolean checkPP = false;
	private int ID_PLAY = 0;
	MusicAdapter adapter;
	private ProgressDialog proGress;
	private AdView adView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		init();
		parser = new ParserMusic(this);
		mData = new loadData();
		if (Utils.isNetworkAvailable(this)) {
			mData.execute(page);
		}
		
		lv.setOnItemClickListener(this);
	}
	public void init() {
		lv = (ListView) findViewById(R.id.list);
        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View viewFooter = layoutInflater.inflate(R.layout.layout_footer, null);
        viewFooter.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                new loadData().execute(page);
            }
        });
        lv.addFooterView(viewFooter);
        imgPlay = (ImageView) findViewById(R.id.play_button);
		txtName = (TextView) findViewById(R.id.txtNameMusic);
		adView = (AdView) findViewById(R.id.adView);
		adView.loadAd(new AdRequest());
		txtName.setSelected(true);
		jsonParser = new ParserJson();
		mPlayer = new MediaPlayer();
		mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		mPlayer.reset();
		mPlayer.setOnBufferingUpdateListener(this);
		mPlayer.setOnCompletionListener(new OnCompletionListener() {
			@Override
			public void onCompletion(MediaPlayer mp) {
				try {

					if (item + 1 < countItems) {
						urlLoaded = new loadURL().execute(
								arrData.get(item + 1).getUrl()).get();
						new PlayMusicAnsytask().execute(urlLoaded);
						item += 1;
					} else {
						item = 0;
						urlLoaded = new loadURL().execute(
								arrData.get(0).getUrl()).get();
					}
				} catch (Exception e) {
					// TODO: handle exception
				}

			}
		});

	}

	class loadData extends AsyncTask<Integer, Void, ArrayList<objData>> {
		ProgressDialog mProgress;

		@Override
		protected void onPreExecute() {
			mProgress = new ProgressDialog(MainActivity.this);
			mProgress.setMessage("Load Data");
			mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgress.setCancelable(true);
			mProgress.setOnCancelListener(new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					dialog.cancel();
					dialog.dismiss();
					mData.cancel(true);
					finish();
				}
			});
			mProgress.show();
		}

		@Override
		protected ArrayList<objData> doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			arrData = new ArrayList<objData>();
			arrData = parser.getData(page);
			if (arrData != null) {
				
				
				return arrData;
			} else {
				return null;
			}
		}

		@Override
		protected void onPostExecute(ArrayList<objData> result) {
			if (result != null && result.size() > 0) {
				page+=1;
				countItems = result.size();
				adapter = new MusicAdapter(MainActivity.this, 1, result);
				lv.setAdapter(adapter);
				adapter.notifyDataSetChanged();
			} else {
				AlertDialog.Builder mAlert = new AlertDialog.Builder(
						MainActivity.this);
				mAlert.setTitle("Không có dữ liệu");
				mAlert.setMessage(
						"Đã xảy ra lỗi trong quá trình tải dữ liệu,Bạn có muốn tải lại không ?")
						.setPositiveButton("Có",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										try {
											mData = new loadData();
											mData.execute(1);
										} catch (Exception ex) {
											Log.e("error load", ex.toString());
										}
									}
								})
						.setNegativeButton("Không",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.cancel();
										dialog.dismiss();
										mProgress.cancel();
										mProgress.dismiss();
										mData.cancel(true);
										finish();
									}
								});
				AlertDialog mAlertDialog = mAlert.create();
				mAlertDialog.show();
			}
			mProgress.dismiss();
		}
	}

	class loadURL extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params) {
			Log.e(TAG, "test: " + params[0]);
			String json = jsonParser.getJson(params[0]);
			if (null != json) {
				try {
					JSONObject object = (JSONObject) new JSONTokener(json)
							.nextValue();
					JSONArray mJsonArray = object.getJSONArray("nonstopdetail");
					JSONObject objJson = mJsonArray.getJSONObject(0);
					return objJson.getString(URL);
				} catch (JSONException e) {
					Log.e("json", e.toString());
				}
			}
			return json;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			// new PlayMusicAnsytask().execute(result);
		}
	}

	/*
	 * Play music song with link url
	 */
	private class PlayMusicAnsytask extends AsyncTask<String, Void, Void> {
		@Override
		protected void onPreExecute() {
			proGress = new ProgressDialog(MainActivity.this);
			proGress.setMessage(getResources().getString(
					R.string.ms_loading_data));
			proGress.setCancelable(true);
			proGress.setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					dialog.dismiss();
					mPlayer.release();
					mPlayer = new MediaPlayer();
					// mButton.setImageResource(R.drawable.btn_play);
					ID_CHECK_FIRST = -10000;
					cancel(true);
				}
			});
			proGress.show();
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected Void doInBackground(String... params) {
			// final String url = params[0];
			Log.e(TAG, "resourse: " + params[0]);
			// if (cancel == true && isCancelled() == false) {
			try {
				mPlayer.reset();
				mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
				mPlayer.setDataSource(params[0]);
				mPlayer.prepareAsync();
				mPlayer.setOnPreparedListener(new OnPreparedListener() {
					@Override
					public void onPrepared(MediaPlayer mp) {
						proGress.dismiss();
						mp.start();
					}
				});
				mPlayer.setOnErrorListener(new OnErrorListener() {
					@Override
					public boolean onError(MediaPlayer mp, int what, int extra) {
						proGress.dismiss();
						return false;
					}
				});
				mPlayer.setWakeMode(getApplicationContext(),
						PowerManager.PARTIAL_WAKE_LOCK);
				// primarySeekBarProgressUpdater();
			} catch (Exception e) {
				Log.e("Error", e.toString());
			}
			// }
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
		}

	}

	public void primarySeekBarProgressUpdater() {

		try {
			if (mPlayer.isPlaying()) {
				notification = new Runnable() {
					public void run() {
						primarySeekBarProgressUpdater();
					}
				};
				handler.postDelayed(notification, 1000);
			} else {
			}
		} catch (Exception e) {
			Log.e("error seek bar", e.toString());
		}
	}

	public void NextSong(Boolean check) {
		if (check == true) {

		}
	}

	@Override
	public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		itemMainClick(position);

	}

	/**
	 * Play music
	 * 
	 * @param v
	 */
	public void PlayMusic(View v) {
		Bitmap bitmapPause = BitmapFactory.decodeResource(this.getResources(),
				R.drawable.btn_pause);
		Bitmap bitmapPlay = BitmapFactory.decodeResource(this.getResources(),
				R.drawable.btn_play);

		if (ID_CHECK_FIRST >= 0) {
			if (!mPlayer.isPlaying()) {
				mPlayer.start();
				imgPlay.setImageBitmap(bitmapPause);
				checkPP = true;
			} else {
				mPlayer.pause();
				imgPlay.setImageBitmap(bitmapPlay);
				checkPP = false;
			}
		} else {
			Toast.makeText(MainActivity.this, "Hãy chọn bài để nghe !",
					Toast.LENGTH_SHORT).show();
		}

	}

	/**
	 * image button preview click
	 * 
	 * @param v
	 */
	public void PreviewMusic(View v) {
		if (ID_PLAY > 0) {
			itemMainClick(ID_PLAY - 1);
		} else {
			Toast.makeText(MainActivity.this, "Không thể thực hiện",
					Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * image button next click
	 * 
	 * @param v
	 */
	public void NextMusic(View v) {
		if (ID_PLAY < adapter.getCount() - 1) {
			itemMainClick(ID_PLAY + 1);
		} else {
			Toast.makeText(MainActivity.this, "Không thể thực hiện",
					Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * Item click
	 * 
	 * @param position
	 */
	public void itemMainClick(int position) {
		try {
			String urlLoaded = new loadURL().execute(
					arrData.get(position).getUrl()).get();
			// Log.e(TAG, "url: "+ urlLoaded);
			new PlayMusicAnsytask().execute(urlLoaded);
			txtName.setText(arrData.get(position).getName());
			imgPlay.setImageResource(R.drawable.btn_pause);
			CHECK_CLICK = false;
			linkCurrent = urlLoaded;
			ID_CHECK_FIRST = arrData.get(position).getPage();
		} catch (Exception e) {
			Log.e("error main click", e.toString());
		}
	}

	@Override
	public void onBackPressed() {
		DialogQuitApp dialog = new DialogQuitApp(this,
				getString(R.string.message_quit_app)) {
			@Override
			protected void onClickButtonDone() {
				finish();
			}
		};
		dialog.show(findViewById(R.id.main));
	}

	@Override
	protected void onDestroy() {
		handler.removeCallbacks(notification);
		if (mPlayer.isPlaying()) {
			mPlayer.pause();
			mPlayer.release();
		} else {
			mPlayer.release();
		}
		super.onDestroy();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}
}
